<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<!DOCTYPE html>
<html>
<head>


    <!-- CSS files start -->

    <link rel="stylesheet" href="/landlord/css/paggingAndPullRefresh.css"/>

    <link href="/landlord/css/details_all.css" rel="stylesheet" type="text/css" media="all"/>

    <script type="text/javascript">

        top.top.setTitle("我的房源");

    </script>

</head>
<body>

<%--

<div id="wrapper">
    <ul id="display">
    </ul>
</div>
--%>


<div class="ac-content" style="position: absolute;z-index: 600">
    <div id="J-page" class="ac-page-dd">
        <div class="ac-page-nav">
            <p class="ac-page-cur">1</p>
            <p class="ac-page-total">10</p>
        </div>
        <i class="ac-page-top"></i>
    </div>
</div>


<div class="websiteWrapper">


    <!-- page wrapper starts -->

    <div class="pageWrapper portfolioOnePageWrapper">


        <!-- portfolio wrapper starts -->

        <div class="portfolioOneWrapper" id="wrapper" style="left: 0;">


            <!-- portfolio item starts  -->

            <ul id="display" style="">

            </ul>

        </div>
    </div>
</div>

<%--使用缓存--%>
<script src="/landlord/js/iscroll.js"></script>
<script type="text/javascript" src="/landlord/js/paggingAndPullRefresh_all.js"></script>


<%--删除事件--%>
<script type="text/javascript">


    //删除逻辑.点击删除后等待5s后才行删除


    //被保存的计时器
    let timers = [];

    //删除函数
    function rm(id) {
        $.post('/landlord/myRooms/remove', {id: id}, function () {
            let item = $('#room_' + id);
            item.slideUp(500, function () {
                item.remove();

                //更改条目数
                $J.totalSub(1);
                myScroll.refresh();
            });
        }).error(function (err) {
            alert(err.responseText)
        });
    }

    //点击删除按钮
    $(document).on('click', '.singleProjectDeleteButton', function () {


        let del = $(this);

        //被删除的房源id
        let id = del.attr('roomId');

        //将其他内容隐藏
        del.parent().prev().hide();
        del.parent().prev().prev().hide();

        //显示立即删除面板
        del.parent().before('<h2 roomId=' + id + ' class="remove-panel" style="color: #636281;text-align: center;padding-top: 80px;padding-bottom: 60px">五秒内可撤销(轻触立即删除)</h2>');

        //隐藏编辑按钮
        del.next().hide();

        //删除按钮切换为撤销按钮
        del.removeClass('singleProjectDeleteButton');
        del.addClass('singleProjectDeleteButton-revocation');

        del.text("撤销");


        $('#room_'+id+' .remove-panel').click(function () {
            //清除超时时间
            clearTimeout(timers[id]);
            rm(id);
        });


        timers[id] = setTimeout(function () {
            rm(id);
        }, 5000);

    });


    //点击撤销按钮
    $(document).on('click', '.singleProjectDeleteButton-revocation', function () {


        let revocation = $(this);

        let id = revocation.attr('roomId');

        //移除计时器
        clearTimeout(timers[id]);

        //移除面板
        revocation.parent().parent().find('.remove-panel').remove();

        //把必要的组件重新显示
        revocation.parent().prev().show();
        revocation.parent().prev().prev().show();
        revocation.next().show();

        //重新变回删除按钮
        revocation.addClass('singleProjectDeleteButton');
        revocation.removeClass('singleProjectDeleteButton-revocation');
        revocation.text("删除");

    });


</script>


<style>

    .room-state{
        font-size: 5px;
        margin-left: 5px;
    }

</style>

<script type="text/javascript">


    var $J = $('#J-page');

    $J.pageination({
        always: false,
        startPos: 60,
        stepHeight: 500,
        total: 0
    });


    initParam = {
        id: "wrapper",
        pullDownAction: Refresh,
        pullUpAction: Load,

        scroll: function (y) {
            $J.onScroll(y);
        },

        scrollEnd: function (y) {
            $J.scrollEnd(y);
        }

    };

    refresher.init(initParam);


    $J.on('click.top', function (event) {
        $J.onScroll(myScroll.startY);
        refresher.myScroll.scrollTo(0, myScroll.minScrollY, 1000, false);
    });


    let ul = $("#display");
    let cPage = 1;
    let tPageSize = 3;

    function Refresh() {
        $.post('/landlord/myRooms', {page: 1, pageSize: tPageSize}, function (result) {
            ul.empty();
            appendLs(result);
            $J.updateTotal(result.length);
            cPage = 2;
            myScroll.refresh();
        });

    }


    function Load() {

        $.post('/landlord/myRooms', {page: cPage, pageSize: tPageSize}, function (result) {
            appendLs(result);
            $J.totalAdd(result.length);
            cPage++;
            myScroll.refresh();
        });
    }


    function searchSec(result, q) {


        //更改标题
        top.top.setTitle("搜索结果");

        //更改标记位
        isSearch = true;

        ul.empty();

        $J.updateTotal(result.length);

        appendLs(result);

        cPage = 1;

        myScroll.refresh();

        refresher.myScroll.scrollTo(0, myScroll.minScrollY, 1000, false);


        //修改加载方法

        initParam.pullUpAction = function () {


            var q = args.q;

            //使用ajax进行请求

            args.addition.page = cPage;

            q = q + '&' + $.param(args.addition, true);

            $.ajax({
                method: args.method,
                type: args.type,
                url: args.url,
                data: q,
                success: function (result) {
                    appendLs(result);
                    $J.totalAdd(result.length);
                    cPage++;
                    myScroll.refresh();
                },
                error: function () {
                    alert("加载失败");
                }
            });

        };


        initParam.pullDownAction = function () {
            var q = args.q;

            //使用ajax进行请求
            args.addition.page = 1;

            q = q + '&' + $.param(args.addition, true);

            $.ajax({
                method: args.method,
                type: args.type,
                url: args.url,
                data: q,
                success: function (result) {
                    ul.empty();
                    appendLs(result);
                    $J.updateTotal(result.length);
                    cPage = 2;
                    myScroll.refresh();
                },
                error: function () {
                    alert("加载失败");
                }
            });

        };

    }


    var isSearch = false;

    //开启搜索
    var args = {
        method: 'post',
        addition: { //附加参数
            fields: ['name', 'location'],
            page: 1,
            pageSize: tPageSize
        },
        url: '/landlord/myRooms/search',
        onsuccess: searchSec
    };
    top.searchAble(args);


    //切换房源状态
    function state(id, state) {


        //房源的状态位
        let stateH = $('#room_' + id + ' .room-state');

        let stateB = $('#room_' + id + ' .portfolioOneItemButtonsWrapper');

        //清空状态位
        stateB.empty();

        switch (state) {
            case 'published':
                stateH.css('color', 'green');
                stateH.text("已发布");

                stateB.append(' <a roomId="' + id + '" class="singleProjectDeleteButton">删除</a>' +
                    '                            <a class="portfolioOneEditButton" target="_blank" href=' + "/landlord/edit?id=" + id + ' >编辑</a>');

                break;
            case 'unpublished':
                stateH.css('color', 'gray');
                stateH.text("未发布");

                stateB.append(' <a roomId="' + id + '"  class="singleProjectDeleteButton">删除</a>' +
                    '                            <a class="portfolioOneEditButton" target="_blank" href=' + "/landlord/edit?id=" + id + ' >编辑</a>');
                break;

            case 'using':
                stateH.css('color', 'red');
                stateH.text("使用中");

                break;
        }


    }

    //插入多个房源
    function appendLs(ls) {

        for (let i in ls) {

            appendOne(ls[i]);

        }

    }


    //出入一个房源
    function appendOne(room) {

        let s = room2text(room);

        ul.append(s);

        myScroll.refresh();

        //异步查看房间的状态
        $.get('/room/state', {roomId: room.id}, function (s) {

            state(room.id, s);

        });

    }


    function room2text(room, hide) {


        let imgUrl;

        if (room.images && room.images.length > 0) {
            imgUrl = '/resource/preview/2/' + room.images[0] + '.jpg';
        }
        else {
            //产生一个随机数从缺省图片中选出一张
            imgUrl = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1546502159888&di=ba8195972eb78359422bb19a4e6b59d1&imgtype=0&src=http%3A%2F%2Fp2.so.qhimgs1.com%2Ft01481b7750ea1d245e.png';
        }


        let s = '' +
            '                <li id=' + "room_" + room.id + ' style="height: 500px;;width :96%;left: 0;margin-left: 2%;padding-top:20px;background-color: transparent;line-height: 15px;'+(hide?'display: none;':'')+'">' +
            '' +
            '' +
            '                    <div class="portfolioOneItemWrapper" style="max-height: 495px;">' +
            '                        <a href=' + "/landlord/roomDetails?id=" + room.id + ' target="_blank" class="portfolioOneItemImageWrapper"><img' +
            '                                style="max-height: 300px;object-fit: cover;width: 100%"' +
            '                                src="' + imgUrl + '" alt=""/></a>' +
            '                        <div class="portfolioOneItemInfoWrapper" style="max-height: 200px">' +


            '                            <h3 class="portfolioOneItemTitle">' + room.name + '<span class="room-state"></span></h3>' +
            '                            <div>' + room.location.address + ',' + room.location.detailedDescription + '</div>' +
            '                        </div>' +

            '<div class="portfolioOneItemButtonsWrapper"></div>' +

            '                    </div>' +
            '' +

            '' +
            '                </li>                                                ';

        return s;
    }




    Refresh();

</script>


<%--重新获取焦点时从cookie中获取变化的数据--%>
<script src="https://cdn.staticfile.org/jquery-cookie/1.4.1/jquery.cookie.js"></script>

<script type="text/javascript">


    //首先清空
    $.cookie('deleteRoomId', '');
    $.cookie('editRoomId', '');
    $.cookie('putRoomId', '');

    window.onfocus = function () {


        let roomState = $.cookie('roomState');

        if (roomState) {
            $.cookie('roomState', '');
            let ss = roomState.split('-');


            let id = ss[0];

            let s = ss[1];

            //切换房源状态
            state(id, s);

        }


        let deleteRoomId = $.cookie('deleteRoomId');

        let editRoomId = $.cookie('editRoomId');

        let putRoomId = $.cookie('putRoomId');


        if (deleteRoomId) {

            $.cookie('deleteRoomId', '');

            let item = $('#room_' + deleteRoomId);

            item.slideUp(500, function () {
                item.remove();
                $J.totalSub(1);
            });

        }

        if (putRoomId) {

            //无论是否请求成功都将该putRoomId移除
            $.cookie('putRoomId', '');

            //如果有新添加的房间

            if (!isSearch) {//如果非搜索状态

                $.post('/landlord/myRooms/get', {id: putRoomId}, function (room) {

                    let s = room2text(room, true);

                    //向前追加
                    ul.prepend(s);

                    //总数加1
                    $J.totalAdd(1);

                    let n = $("#room_" + room.id);

                    if ($('.ac-page-cur').text() === '1') {
                        n.slideDown(600, function () {
                            myScroll.refresh();
                        });

                    } else {

                        //滚动到顶端
                        refresher.myScroll.scrollTo(0, refresher.myScroll.minScrollY, 1000, false);

                        setTimeout(function () {
                            n.slideDown(500, function () {
                                myScroll.refresh();
                            });
                        }, 1000);
                    }


                    //异步查看房间的状态
                    $.get('/room/state', {roomId: room.id}, function (s) {

                        state(room.id, s);

                    });

                });

            }

        }


        if (editRoomId) {

            $.cookie('editRoomId', '');

            let item = $('#room_' + editRoomId);

            if (item) {

                //重新获取房源,
                $.post('/landlord/myRooms/get', {id: editRoomId}, function (room) {

                    //先将房源隐藏
                    item.slideUp(300, function () {

                        //修改数据

                        let imgUrl;

                        if (room.images && room.images.length > 0) {
                            imgUrl = '/resource/preview/2/' + room.images[0] + '.jpg';
                        }
                        else {
                            let random = Math.floor(Math.random() * 14) + 1;
                            //产生一个随机数从缺省图片中选出一张
                            imgUrl = '/landlord/images/vacant/' + random + ".jpg";
                        }

                        //图片的url
                        item.find('img').replaceWith('<img style="max-height: 300px;object-fit: cover;width: 100%" src=' + imgUrl + '>');


                        //房间名称
                        let name = item.find('.portfolioOneItemTitle');

                        name.next().replaceWith('<div>' + room.location.address + ',' + room.location.detailedDescription + '</div>');

                        name.replaceWith('<h4 class="portfolioOneItemTitle">' + room.name + '</h4>');

                        //再以将房源显示出来
                        item.slideDown(300);
                    });

                });


            }

        }


    };


</script>


</body>
</html>